#include "Discover.h"
#include <iostream>
using namespace std;
Discover::Discover():
	estado(ST_DISC_NO_INIT)
{
	memset(&DestAddr, 0, sizeof(DestAddr));
}

Discover::~Discover()
{
}

bool Discover::tick()
{
	bool ret = false;

	switch (estado) {
	case ST_DISC_NO_INIT:
		init();
		if(openSocket(SOCK_DGRAM, IPPROTO_UDP, SO_BROADCAST, 4000))
		{
			estado = ST_DISC_RECV;
			timerPooling = clock();
			DestAddr.sin_family = AF_INET;
			DestAddr.sin_port = htons(4000);
			DestAddr.sin_addr.s_addr = inet_addr("255.255.255.255");
		}
		break;
	case ST_DISC_RECV:
		if (IsRxData())
		{
			char data[100];
			memset(data, 0, sizeof(data));
			sockaddr_in RemoteAddr;
			//hay algo para recibir
			int lenAddress = sizeof(RemoteAddr);

			int len = recvfrom(data, sizeof(data), (SOCKADDR *)&RemoteAddr, &lenAddress);
			cout<<"Llega data: "<<data<<" de: "<<inet_ntoa(RemoteAddr.sin_addr)<<endl;
			if (validData(data, len))
			{
				nodo.addr = RemoteAddr;
				ret = true;
			}

		}

		break;
	}

	return ret;
}

bool Discover::validData(char* buff, int len)
{
	return true;
}
bool Discover::getNuevoNodo(Nodo *nodo)
{
	nodo->id = this->nodo.id;
	nodo->addr = this->nodo.addr;
	return true;
}
